<?php
class EmoTag_Manager extends Model {
	
	private $_current_blogger_id;
	
	function EmoTag_Manager() {
		parent::Model();
		$this->_current_blogger_id = 0;
		$this->load->library('common');
	}
	
	function SetCurrentBloggerID($blogger_id) {
		$this->_current_blogger_id = $blogger_id;
	}
	
	function _check_blogger_id() {
		if($this->_current_blogger_id == 0) {
			throw new Exception('Invalid Blogger-ID!');
		}
	}
	
	function AddEmoTag($emoTagData) {
		$this->_check_blogger_id();
		
		$parms = array(
			'blogger_id' => $this->_current_blogger_id,
			'post_time' => $emoTagData['post_time'],
			'emo_icon' => $emoTagData['emo_icon'],
			'emo_text' => $emoTagData['emo_text']
		);
		$this->db->insert('nt_emotags', $parms);
	}
	
	function ListEmoTags($per_page, $page_no) {
		$this->_check_blogger_id();
		
		$start = $per_page * $page_no;
		$qry = $this->db->query('SELECT `id`, `post_time`, `emo_icon`, `emo_text` FROM `nt_emotags` WHERE `blogger_id` = ? ORDER BY `post_time` DESC LIMIT ?, ?', array($this->_current_blogger_id, $start, $per_page));
		return $qry->result();
	}
	
	function DeleteEmoTag($blogger_id, $emoTag_id) {
		$this->_check_blogger_id();
		$this->db->query('DELETE FROM `nt_emotags` WHERE `id` = ? AND `blogger_id` = ?', array($emoTag_id, $blogger_id));
	}
	
	function CountEmoTags() {
		$this->_check_blogger_id();
		
		$qry = $this->db->query('SELECT COUNT(`id`) AS `num` FROM `nt_emotags` WHERE `blogger_id` = ?', array($this->_current_blogger_id));
		return $qry->row()->num;
	}
	
	// following functions are for experiment only, integrated with imifield.com
	function IM_AddUser($blogger_id, $userkey) {
		$fpath = $_SERVER['DOCUMENT_ROOT'] . '/data/imifield_userkeys.txt';
		if(!file_exists($fpath)) {
			return FALSE;
		}
		
		$users = json_decode(file_get_contents($fpath), TRUE);
		if(is_array($users)) {
			foreach($users as $u) {
				if($u['blogger_id'] == $blogger_id) {
					// already added, quit
					return FALSE;
				}
			}
			array_push($users, array(
				'blogger_id' => $blogger_id,
				'userkey' => $userkey
			));
			file_put_contents($fpath, json_encode($users));
			return TRUE;
		} else {
			// loading users-data error
			return FALSE;
		}
	}
	
	function IM_PostEmoTag($userkey, $emo_text) {
		$fpath = $_SERVER['DOCUMENT_ROOT'] . '/data/imifield_userkeys.txt';
		if(!file_exists($fpath)) {
			return FALSE;
		}
		
		$users = json_decode(file_get_contents($fpath), TRUE);
		if(is_array($users)) {
			foreach($users as $u) {
				if($u['userkey'] == $userkey) {
					// add a emoTag
					$parms = array(
						'blogger_id' => $u['blogger_id'],
						'post_time' => $this->common->Now(),
						'emo_icon' => 'BB0', // default icon
						'emo_text' => $emo_text
					);
					$this->db->insert('nt_emotags', $parms);
					return TRUE;
				}
			}
			// not added, quit
			return FALSE;
		} else {
			// loading users-data error
			return FALSE;
		}
	}
	
}
?>